﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Utilities;
using StockCommon.baseclass;
using StockCommon.Calendar;

namespace StockCommon.data
{
    public class StockDailySellBuyServices : DBAccess
    {
        public static DateTime getMaxSBDate( TwnStockMarketType t)
        {
            DateTime dn = DateTime.Now;
            DateTime dt = new DateTime(dn.Year, dn.Month, dn.Day, 16, 30, 0);
            if(t.Equals(TwnStockMarketType.上櫃))
                dt = new DateTime(dn.Year, dn.Month, dn.Day, 15, 40, 0);
            
            if (CalenderHelper.isWorkDay(dn))
                if (dn.CompareTo(dt) > 0)
                {
                    return dn;
                }
            dn = dn.AddDays(-1);
            while (true)
            {
                if (CalenderHelper.isWorkDay(dn))
                    return dn;
                dn = dn.AddDays(-1);
            }
        }

        public static int getStockCount(DateTime date, TwnStockMarketType mtype)
        {
            String m = "";
            switch (mtype)
            {
                case TwnStockMarketType.上市:
                    m = "tse";
                    break;
                case TwnStockMarketType.上櫃:
                    m = "otc";
                    break;
            }
            String ds = DateUtils.toShortDateFormat(date);

            String pat = "select COUNT(*) as c from StockIndex with (NOLOCK) where StockIndex.市場='{0}' and StockIndex.代號 in (select distinct SBDetails.StockCode from SBDetails with (NOLOCK) where SBDetails.日期='{1}')";
            String sql = string.Format(pat, m, ds);
            int c = getContext().ExecuteQuery<int>(sql).First();
            return c;

        }

    }
}
